package com.kyomonn.talkischeap.QuestionBank;

import android.os.Bundle;
import android.widget.Button;
import android.widget.GridView;
import android.widget.Toast;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.kyomonn.talkischeap.R;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Objects;

public class QuestionPanelActivity extends AppCompatActivity {

    private String bankName;
    public QuestionItem[] questions;
    private int score = 0;
    private int[] userAnswers; // 保存用户的选择

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_question_panel);
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.activity_question_panel), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

        // 设置 Toolbar
        setSupportActionBar(findViewById(R.id.tb_activity_question_panel));
        Objects.requireNonNull(getSupportActionBar()).setDisplayHomeAsUpEnabled(true); // 显示返回箭头

        bankName = getIntent().getStringExtra("bank_name");
        loadQuestionsFromAsset();

        GridView gvQuestionPanel = findViewById(R.id.gv_activity_question_panel);
        gvQuestionPanel.setAdapter(new QuestionAdapter(this, R.layout.item_question, questions));

        Button btnSubmit = findViewById(R.id.btn_submit);

        // 初始化用户答案数组，默认值为 -1 表示未选择
        userAnswers = new int[questions.length];

        // 设置点击监听器
        btnSubmit.setOnClickListener(v -> {
            score = 0;
            for (int i = 0; i < questions.length; i++) {
                if (userAnswers[i] == questions[i].getCorrectAnswerIndex()) {
                    score++;
                }
            }
//            tvScore.setText("得分：" + score + " / " + questions.length);
            Toast.makeText(this, "得分：" + score + " / " + questions.length, Toast.LENGTH_SHORT).show();
        });
    }

    private void loadQuestionsFromAsset() {
        try {
            InputStream is = getAssets().open(bankName + ".json");
            int size = is.available();
            byte[] buffer = new byte[size];
            is.read(buffer);
            is.close();

            String json = new String(buffer, StandardCharsets.UTF_8);

            JSONArray jsonArray = new JSONArray(json);
            questions = new QuestionItem[jsonArray.length()];
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject obj = jsonArray.getJSONObject(i);
                String questionText = obj.getString("question");
                JSONArray optionsArray = obj.getJSONArray("options");
                String[] options = new String[optionsArray.length()];
                for (int j = 0; j < optionsArray.length(); j++) {
                    options[j] = optionsArray.getString(j);
                }
                int correctAnswerIndex = obj.getInt("correctAnswerIndex");
                questions[i] = new QuestionItem(questionText, options, correctAnswerIndex);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 在 adapter 中回调设置用户答案
    public void setUserAnswer(int position, int answerIndex) {
        if (position >= 0 && position < userAnswers.length) {
            userAnswers[position] = answerIndex;
        }
    }

    @Override
    public boolean onSupportNavigateUp() {
        onBackPressed();
        return true;
    }
}